package com.dp.mallchat.common.common.lock;

import com.dp.mallchat.common.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;

import static com.dp.mallchat.common.common.domain.enums.CommonErrorEnum.LOCK_OUT_TIME;

/**
 * @Author: dupeng
 * @CreateTime: 2024-06-06  10:54
 * @Description: 编程式分布式锁实现统一入口
 */
@Service
@Slf4j
public class LockService {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 执行任务有返回值
     * @param key        加锁唯一标识
     * @param waitTime   等待时间
     * @param timeUnit    时间单位
     * @param supplier      任务
     * @param <T>
     * @return         返回值
     */
    public <T> T executeWithLock(String key, long waitTime, TimeUnit timeUnit, SupplierThrow<T> supplier) throws Throwable {
        RLock lock = redissonClient.getLock(key);
        boolean isSuccess = lock.tryLock(waitTime, timeUnit);
        if (!isSuccess) {
            throw new BusinessException(LOCK_OUT_TIME);
        }
        try {
            return supplier.get();
        } finally {
            //确定锁被占用，并且锁的是当前线程，防止因为超时导致锁释放，再次去释放锁
            if (lock.isLocked() && lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }


    public <T> T executeWithLock(String key, SupplierThrow<T> supplier) throws Throwable {
        return executeWithLock(key, -1, TimeUnit.MILLISECONDS, supplier);
    }


    /**
     * 执行任务不需要返回值
     * @param key       加锁唯一标识
     * @param waitTime  等待时间
     * @param timeUnit  时间单位
     * @param runnable  业务
     * @throws Throwable    异常
     */
    public void runWithLock(String key, long waitTime, TimeUnit timeUnit, Runnable runnable) throws Throwable {
        RLock lock = redissonClient.getLock(key);
        boolean isSuccess = lock.tryLock(waitTime, timeUnit);
        if (!isSuccess) {
            throw new BusinessException(LOCK_OUT_TIME);
        }
        try {
            runnable.run();
        } finally {
            lock.unlock();
        }
    }

    public void runWithLock(String key, Runnable runnable) throws Throwable {
        runWithLock(key, -1, TimeUnit.MILLISECONDS, runnable);
    }


    @FunctionalInterface
    public interface SupplierThrow<T> {

        /**
         * Gets a result.
         *
         * @return a result
         */
        T get() throws Throwable;
    }

}
